//
//  XGL_PersonalPublishXGL_LiveViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/21.
//

import UIKit
import AVFoundation

class XGL_PersonalPublishXGL_LiveViewController: UIViewController,CustomNavgationBar{
    lazy var hudView: XGL_CustomHudView = XGL_CustomHudView()
    var titleText: UITextField!
    var imagePickerView: ImagePickerView!
    
    var publishTitle: String{
        return self.titleText.text ?? ""
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.createCustomBackgroundView()
        self.createXglView()
        self.creatClearNavigationBar(title: "Create Room")
    }
    

}

extension XGL_PersonalPublishXGL_LiveViewController{
    @objc private func sendAction(){
        let alertView = XGL_PersonalPublishLiveAlertView()
        alertView.showAlertView {
            self.openCamera { [weak self] in
                guard let `self` = self else { return }
                self.publishLive()
            }
        }
        self.view.addSubview(alertView)
        alertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}

extension XGL_PersonalPublishXGL_LiveViewController{
    func openCamera(complete: @escaping ()->Void) {
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        if authStatus == .notDetermined {
            AVCaptureDevice.requestAccess(for: .video) { (res) in
                DispatchQueue.main.async {
                    complete()
                }
            }
        }else{
            complete()
        }
    }
    
    private func publishLive(){
        let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
        guard authStatus == .authorized else {
            let actionController = UIAlertController(title: "Warm reminder", message: "Please open camera permissions", preferredStyle: .alert)
            let action3 = UIAlertAction(title: "Sure", style: .default) { _ in
                if let url = URL(string: UIApplication.openSettingsURLString){
                    UIApplication.shared.open(url)
                }
            }
            let action2 = UIAlertAction(title: "Cancel", style: .cancel)
            actionController.addAction(action2)
            actionController.addAction(action3)
            self.present(actionController, animated: true)
            return
        }
        guard self.publishTitle.isEmpty == false else {
            MXProgressHUD.hudWithText("Please enter Photo Title")
            return
        }
        guard let image = self.imagePickerView.pickImages.first else {
            MXProgressHUD.hudWithText("Please select Photo")
            return
        }
        self.hudView.backgroundColor = .clear
        self.hudView.hudView.startAnimation()
        self.view.addSubview(self.hudView)
        self.hudView.snp.makeConstraints { make in
            make.width.centerX.bottom.equalToSuperview()
            make.top.equalTo(PanNavibarH)
        }
        self.uploadImageRequest(image: image) { [weak self] url in
            guard let `self` = self else { return }
            self.publishDataRequest(image: image,imageurl: url)
        }
    }
}

extension XGL_PersonalPublishXGL_LiveViewController{
    private func uploadImageRequest(image: UIImage,complete: ((_ url: String)->Void)? = nil){
        PanRequestManager<XGL_RequestBaseResponse<Response>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .Upload(image: image, file: "file"))) { result in
            switch result{
            case .success(let response):
                if let block = complete {
                    block(response.resultJson)
                }
                break
            default:
                break
            }
        }
    }
    
    private func publishDataRequest(image: UIImage,imageurl: String){
        let data = PublishParamsData(data1: "1",data2: self.publishTitle,data3: imageurl)
        PanRequestManager<XGL_RequestBaseResponse<PublishData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .PublishData(data: data))) { result in
            self.hudView.dismiss()
            switch result{
            case .success(let response):
                if let model = response.resultData {
                    let vc = XGL_LiveRoomAnchorViewController()
                    vc.cover = image
                    vc.liveId = model.id
                    self.navigationController?.pushViewController(vc)
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_PersonalPublishXGL_LiveViewController{
    private func createXglView(){
       
        self.titleText = UITextField().then({ make in
            make.textColor = UIColor.white
            make.font = UIFont.pingfangSC_Regular(fontSize: 16.0)
            make.attributedPlaceholder = "Enter here".attributesColor(UIColor.hexColor("#A2A2A2"),UIFont.pingfangSC_Regular(fontSize: 16.0))
        })
        let titleView = XGLPublishUIManager.creatInputTextItemView(title: "Photo Title", inputText: self.titleText)
        
        self.imagePickerView = ImagePickerView().then({ make in
            make.defaultUploadIcon = XGLPublishUIManager.createUploadIocn()
            make.deleteIcon = imageWithName("icon_image_pick_delete")
            make.imageNumSingleLine = 2
            make.maxImageSelectCount = 1
            make.imageRotio = 163.0 / 117.0
            make.imageSpace = 20.0
            make.pickerType = .image
        })
        let pickerView = XGLPublishUIManager.createCommonItemView(title: "Photo", commonView: self.imagePickerView)
       
        let sendButton = UIButton().then { make in
            make.setTitle("Send", for: .normal)
            make.setTitleColor(UIColor.hexColor("#191A1D"), for: .normal)
            make.titleLabel?.font = UIFont.pingfangSC_Regular(fontSize: 18.0)
            make.backgroundColor = UIColor.hexColor("#80FFE6")
            make.layerCornerRadius = 24.0
            make.addTarget(self, action: #selector(self.sendAction), for: .touchUpInside)
        }
        self.view.addSubviews([titleView,pickerView,sendButton])
        titleView.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(32.0 + PanNavibarH)
            make.left.equalTo(15.0)
        }
        pickerView.snp.makeConstraints { make in
            make.centerX.width.equalToSuperview()
            make.top.equalTo(titleView.snp.bottom).offset(25.0)
        }
        sendButton.snp.makeConstraints { make in
            make.left.equalTo(15.0)
            make.centerX.equalToSuperview()
            make.bottom.equalTo(-BottomHeight-42.0)
            make.height.equalTo(48.0)
        }
    }
}
